<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="classifyName">
              <el-input v-model="filters.classifyName" clearable placeholder="服务分类名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增 </el-button>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <!-- 列表 -->
      <tree-table :tableHeight="'750px'" id="scrollDiv" ref="tableRow" :height="maxHeight" :key="tableKey" :columns="columns" :data="treeTableList" :eval-func="func" :loading="loadingIns" :expand-all="expandAll" border>
        <el-table-column align="center" label="分类ID" prop="serverClassifyId" width="90"> </el-table-column>
        <el-table-column align="center" label="分类Logo" width="120">
          <template slot-scope="scope">
            <el-image title="点击可预览" :src="scope.row.classifyLogo" fit="cover" :preview-src-list="[scope.row.classifyLogo]" :z-index="scope.$index"> </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="分类描述" prop="classifyContent"> </el-table-column>
        <el-table-column align="center" label="是否专属商户" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.serverDefault === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否开放服务" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.openFlag === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="100" label="创建人" prop="createUserName"> </el-table-column>
        <el-table-column align="center" width="140" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column align="center" width="100" label="修改人" prop="modifyUserName"> </el-table-column>
        <el-table-column align="center" width="140" label="修改时间" prop="modifyDate"> </el-table-column>
        <el-table-column align="center" width="80" label="状态">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="plain" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="260px">
          <template slot-scope="scope">
            <div class="operate-box">
              <el-button
                v-has="permissionAdd"
                type="text"
                size="mini"
                icon="el-icon-document-add"
                @click="handleClickAdd(scope.row.serverClassifyId, scope.row.parentClassifyId, scope.row.levels)"
                v-if="scope.row.levels < 3"
                >新增下级
              </el-button>

              <el-dropdown trigger="click" size="small" v-if="scope.row.levels === 3">
                <el-button type="primary"> <i class="fa fa-list-ul"></i>绑定 </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionBandSpec" @click.native="handleClickBandSpec(scope.row)">绑定规格 </el-dropdown-item>
                  <el-dropdown-item v-has="permissionBandAttr" @click.native="handleClickBandAttr(scope.row)">绑定属性 </el-dropdown-item>
                  <el-dropdown-item v-has="permissionBandGoods" @click.native="handleClickBandGoods(scope.row)">绑定产品 </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <el-button v-has="permissionEdit" type="text" size="mini" icon="el-icon-edit" @click="handleClickEditor(scope.row)">编辑 </el-button>
              <el-button v-has="permissionBannerImg" type="text" size="mini" icon="el-icon-picture" v-if="scope.row.levels === 2" @click.native="handleAddImg(scope.row)">设置轮播图 </el-button>
              <el-button v-has="permissionUpStatus" type="text" size="mini" icon="el-icon-check" @click="handleIsDisable(scope.row)" v-if="scope.row.state === 0">启用 </el-button>
              <el-button v-has="permissionUpStatus" type="text" size="mini" icon="el-icon-close" @click="handleIsDisable(scope.row)" v-if="scope.row.state === 1">禁用 </el-button>
              <el-button v-has="permissionDelete" v-if="scope.row.state === 0" type="text" size="mini" icon="el-icon-delete" @click="handleClickDelete(scope.row)">删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </tree-table>
    </el-row>

    <BindAttr ref="bindAttr" />
    <BindGoods :show="bandGoodsParam.show" :id-type="1" :id="bandGoodsParam.id" @cancel="cancelBandGoods" />
    <BindSpec :show="bandSpecParam.show" :spec-type="2" :id="bandSpecParam.id" @cancel="cancelBandSpec" />
    <ImageSelect :show="banners.imageSelectShow" folder="classifyBannerImg" :limit="imageLimit" @cancel="banners.imageSelectShow = false" @getUrlList="getUrlList"></ImageSelect>

    <el-dialog title="设置轮播图" :visible.sync="banners.show" center width="833px">
      <el-button type="danger" size="mini" @click="banners.imageSelectShow = true">复制公共图库</el-button>
      <UploadOssFile :limit="banners.limit" :list="banners.list" @getImgVideo="getImgVideo" :showFlag="true" :showSetMain="false" folder="classifyBannerImg" />
      <div slot="footer">
        <el-button @click="saveBannersImag" type="primary">保存</el-button>
        <el-button @click="banners.show = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ServerClassifyApi from '@/api/server/serverClassify';
import TreeTable from '@/components/TreeTable';
import treeToArray from '@/utils/customEval';
import * as message from '@/constants/message';
import BindAttr from '../../components/BindAttr.vue';
import BindGoods from '../../components/BindGoods.vue';
import BindSpec from '../../components/BindSpec.vue';
import ImageSelect from '../../components/ImageSelect.vue';
import UploadOssFile from '../../components/UploadOssFile.vue';
export default {
  name: 'ServerClassifyManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      tableKey: 0,
      columns: [
        {
          text: '服务分类名称',
          value: 'classifyName',
          width: 300,
          align: 'left',
        },
      ],
      treeTableList: [],
      func: treeToArray, // 从树形结构转为数组
      expandAll: false, // 是否展开
      //开始切割的位置
      starSize: 0,
      //结束位置
      endSize: 20,
      totalSize: [],
      loadingIns: false,
      listLoading: true,
      filters: {
        classifyName: '',
      },
      bandGoodsParam: {
        show: false,
        id: '',
      },
      bandSpecParam: {
        show: false,
        id: '',
      },
      banners: {
        show: false,
        list: [],
        limit: 10,
        imageSelectShow: false,
      },
      rowItem: null,
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },

      permissionAdd: 'SYSTEM_MANAGER_SERVER_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_SERVER_INFO_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_SERVER_INFO_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_SERVER_INFO_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_SERVER_INFO_LIST_DELETE',
      permissionBandSpec: 'SYSTEM_MANAGER_SERVER_INFO_LIST_BAND_SPEC',
      permissionBandAttr: 'SYSTEM_MANAGER_SERVER_INFO_LIST_BAND_ATTR',
      permissionBandGoods: 'SYSTEM_MANAGER_SERVER_INFO_LIST_BAND_GOODS',
      permissionBannerImg: 'SYSTEM_MANAGER_SERVER_INFO_LIST_BANNER_IMG',
    };
  },
  computed: {
    imageLimit() {
      return this.banners.limit - this.banners.list.length;
    },
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  components: {
    TreeTable,
    BindAttr,
    BindGoods,
    BindSpec,
    ImageSelect,
    UploadOssFile,
  },
  methods: {
    //懒加载1-节流函数
    throttle(fn, delay) {
      let valid = true;
      return function () {
        if (!valid) {
          //休息时间 暂不执行
          return false;
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
          fn();
          valid = true;
        }, delay);
      };
    },
    //懒加载2-触发方法
    triggerScroll() {
      document.querySelector('#scrollDiv .el-table__body-wrapper').addEventListener('scroll', this.throttle(this.handleScroll, 1000));
    },
    //懒加载3-主体方法
    handleScroll() {
      let scrollTop = document.querySelector('#scrollDiv .el-table__body-wrapper').scrollTop;
      let scrollHeight = document.querySelector('#scrollDiv .el-table__body-wrapper').scrollHeight;
      let clientHeight = document.querySelector('#scrollDiv .el-table__body-wrapper').clientHeight;
      if (this.totalSize.length == this.treeTableList.length) {
        //表示已到底部
        return;
      }
      if (scrollHeight - clientHeight - scrollTop < 30) {
        //监听滚动条到底部
        this.starSize = this.starSize + 20;
        this.endSize = this.endSize + 20;
        let arrOne = this.treeTableList;
        let arrTwo = this.totalSize.slice(this.starSize, this.endSize);
        this.treeTableList = arrOne.concat(arrTwo);
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'warning';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.listData();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    handleClickAdd(serverClassifyId, parentClassifyId, levels) {
      let _this = this;
      _this.$router.push({
        path: '/server/serverClassifyAdd',
        query: { parentId: serverClassifyId, levels: levels, grpParentId: parentClassifyId },
      });
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/server/serverClassifyEdit',
        query: { id: row.serverClassifyId },
      });
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/server/serverClassifyDetail',
        query: { id: row.serverClassifyId },
      });
    },
    handleIsDisable(row) {
      let _this = this;
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        ServerClassifyApi.deleteServerClassify({
          id: row.serverClassifyId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        ServerClassifyApi.deleteServerClassify({
          id: val.serverClassifyId,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickBandSpec(row) {
      this.bandSpecParam.id = row.serverClassifyId;
      this.bandSpecParam.show = true;
    },
    handleClickBandAttr(row) {
      this.$refs.bindAttr.handleCreate({ type: 1, id: row.serverClassifyId });
    },
    handleClickBandGoods(row) {
      this.bandGoodsParam.id = row.serverClassifyId;
      this.bandGoodsParam.show = true;
    },
    cancelBandGoods() {
      this.bandGoodsParam.show = false;
    },
    cancelBandSpec() {
      this.bandSpecParam.show = false;
    },
    async handleAddImg(row) {
      console.log(row);
      const res = await ServerClassifyApi.listBanner({ serverClassifyId: row.serverClassifyId });
      this.rowItem = row;
      this.banners.list = res.data || [];
      this.banners.show = true;
    },
    getImgVideo(val) {
      this.banners.list = val;
    },
    getUrlList(val) {
      const { banners } = this;
      val.forEach((item, index) => {
        this.$set(item, 'showFlag', false);
        this.$set(item, 'sort', banners.list.length + index + 1);
      });
      banners.list = banners.list.concat([...val]);
      banners.imageSelectShow = false;
    },
    async saveBannersImag() {
      const { rowItem, banners } = this;
      await this.$confirm('确定保存', '提示', {});
      await ServerClassifyApi.setBanners({ serverClassifyId: rowItem.serverClassifyId, list: banners.list });
      this.$message.success('设置成功');
      banners.show = false;
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      let _this = this;
      _this.starSize = 0;
      _this.endSize = 20;
      // 获取数据
      _this.treeToArray = [];
      _this.totalSize = [];
      let cond = {
        classifyName: _this.filters.classifyName,
      };
      ServerClassifyApi.listServerClassify(cond)
        .then((res) => {
          _this.totalSize = res.data;
          if (_this.totalSize.length > 20) {
            _this.treeTableList = _this.totalSize.slice(_this.starSize, _this.endSize);
          } else {
            _this.treeTableList = _this.totalSize;
          }
          _this.listLoading = false;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
